<template>
  <div class="app-container">
    <el-form :model="project" label-width="120px">
      <!-- 第一行：项目名称 & 上传文件 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="项目名称">
            <el-input v-model="project.name" placeholder="请输入项目名称" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="截止时间">
            <el-date-picker
              v-model="project.dueTime"
              type="date"
              placeholder="选择截止时间"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
        </el-col>
       <el-col :span="12">
         <el-form-item label="上传需求文件">
           <!-- 如果有原始需求文件，显示链接 -->
           <div v-if="project.docUrl" class="file-display">
             <el-link :href="project.docUrl" target="_blank" type="primary">
               查看原需求文件
             </el-link>
           </div>
           <el-upload
             action=''
             :http-request="customUpload"
             :before-upload="beforeDocUpload"
             :on-success="handleDocSuccess"
             :on-error="handleDocError"
             :show-file-list="true"
             name="file"
           >
             <el-button type="primary">上传文件</el-button>
           </el-upload>
         </el-form-item>
       </el-col>
      </el-row>

      <!-- 第二行：团队组建 & 选择人员 -->
      <el-row :gutter="20">
        <!-- 团队组建 -->
        <el-col :span="8" class="index1">
          <h3>团队组建：</h3>
          <el-descriptions column="1" border class="team-desc">
            <el-descriptions-item label="设计人员">
              <el-link
                @click="selectMember('designerId')"
                class = "clickable"
              >
                {{ getMemberName(project.designerId) || '去选择' }}
              </el-link>
            </el-descriptions-item>
            <el-descriptions-item label="校对人员">
              <el-link
                @click="selectMember('verifierId')"
                class = "clickable"
              >
                {{ getMemberName(project.verifierId) || '去选择' }}
              </el-link>
            </el-descriptions-item>
            <el-descriptions-item label="审定人员">
              <el-link
                @click="selectMember('approverId')"
                class = "clickable"
              >
                {{ getMemberName(project.approverId) || '去选择' }}
              </el-link>
            </el-descriptions-item>
          </el-descriptions>
        </el-col>

        <!-- 选择人员表格 -->
        <el-col :span="16" class="index2" v-if="showSelectionTable">
          <h3>选择{{selectionTitle}}人员</h3>
          <el-table
            :data="memberList"
            border
            class="member-table"
            height="300"
          >
            <el-table-column prop="name" label="姓名" />
            <el-table-column prop="designCount" label="设计项目数" />
            <el-table-column prop="verifyCount" label="校对项目数" />
            <el-table-column prop="approveCount" label="审核项目数" />
            <el-table-column label="操作" width="120">
              <template #default="{ row }">
                <el-link type="primary" style="margin-right: 10px" @click="show(row.id)">查看详情</el-link>
                <el-link type="primary" @click="select(row.id)">选择</el-link>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>

      <!-- 保存按钮 -->
      <div class="footer-btn">
        <el-button type="primary" @click="saveProject">保存项目</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import { listUser,getUserProfile }   from "@/api/system/user";
import {addProbeProject, getProbeProject, getProjectCount, updateProbeProject} from '@/api/system/probeProject'
import { uploadFile } from '@/api/system/probeProject'
import moment from "moment";
export default {
  name: 'ProjectForm',
  data() {
    return {
      project: {
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        id: 1,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedTime: null,
        name: null,
        docUrl: null,
        dueTime: null,
        status: null,
        modelType: null,
        designerId: null,
        verifierId: null,
        approverId: null,
        robeInfoList: null
      },
      userInfo:[],
      memberList: [],
      showSelectionTable: false,
      selectedRoleField: null,
      selectionTitle: '',
      action: 'create',// 新增 or 修改
    };
  },
  async created() {
    // 当前项目设计人员id为当前登录用户id
    // getUserProfile().then(response => {
    //   console.log('当前登录用户信息', response);
    //   this.project.designId = response.data.userId;
    // });
    // 获取所有人员信息
    this.getlistUser();
    // 根据项目id获取项目详情
    if (this.$route.query.id) {
      this.action = 'update';
      const res = await getProbeProject(this.$route.query.id);
      console.log('res',res)
      this.project = res.data;
      console.log('当前项目详情', this.project);
    }
    this.getGroupByStateName();
  },
  methods: {
    // selectGroupByStateNameWithAllUsers
    async getGroupByStateName() {
      try {
        const response = await getProjectCount();
        console.log('获取每个人的设计、校对、审核项目数', response);
        this.memberList = response.data;
        console.log('获取count成功:', this.memberList);
      } catch (error) {
        console.error('获取设计人员信息失败:', error);
      }
    },
    // 获取用户信息
    async getlistUser() {
      try {
        const response = await listUser();
        this.userInfo = response.rows;
      } catch (error) {
        console.error('获取设计人员信息失败:', error);
      }
    },
    // 根据 ID 查名字
    getMemberName(id) {
      if (!id) return '';
      // 从memberList数组中根据据id找名字
      const member = this.userInfo.find(member => member.userId === id);
      console.log('根据id查找名字',id, member);
      return member ? member.nickName : '';
    },
    // 点击“去选择”时加载对应列表
    selectMember(field) {
      console.log('memberList是否有数据：',this.memberList);
      this.selectedRoleField = field;
      this.selectionTitle = field === 'designerId' ? '设计' : field === 'verifierId' ? '校对' : '审定';
      this.showSelectionTable = true;
    },
    // 在右侧表格里选择某行，更新 project 对应字段并隐藏表格
    select(id) {
      console.log('select',id);
      if (this.selectedRoleField) {
        this.project[this.selectedRoleField] = id;
        console.log('选择的人员id', id);
        this.showSelectionTable = false;
      }
    },
    show(id) {
      // 查看人员详情
      this.$router.push({ name: 'UserProjectDetail', query: { id } });
    },
    // 保存
    async saveProject() {
      console.log('要保存的项目：', this.project);

      // 定义校验规则
      const validations = [
        { field: 'name', message: '请输入项目名称' },
        { field: 'dueTime', message: '请选择截止时间' },
        { field: 'docUrl', message: '请上传需求文件' },
        { field: 'designerId', message: '请选择设计人员' },
        { field: 'verifierId', message: '请选择校对人员' },
        { field: 'approverId', message: '请选择审定人员' },
      ];

      // 执行校验
      for (const { field, message } of validations) {
        if (!this.project[field]) {
          this.$message.error(message);
          return;
        }
      }

      this.project.createBy = this.project.designId;
      this.project.createdTime = moment().format('YYYY-MM-DD HH:mm:ss');
      // TODO: 调接口保存 project
      try {
        let res;
        if (this.action === 'update') {
          // 修改
          res = await updateProbeProject(this.project);
        } else {
          // 新增
          res = await addProbeProject(this.project);
        }
        console.log('保存成功:', res);
        if(res.code === 200) {
          this.$message.success('保存成功');
        } else {
          this.$message.error('接口保存失败');
          return;
        }
        // 操作成功后等待一秒返回上一级页面
        setTimeout(() => {
          // 关闭当前tabs
          this.$store.dispatch("tagsView/delView", this.$route);
          // 跳转路由
          this.$router.replace({
            name: "ProbeProject"
          });
        }, 1000);
      } catch (error) {
        console.error('保存失败:', error);
        this.$message.error('保存失败');
      }
    },
    // 自定义上传方法
    customUpload({file}) {
      const formData = new FormData();
      formData.append('file', file); // 将文件添加到 FormData 中
      console.log('上传的文件:', file);
      console.log('FormData 文件对象:', formData.get('file')); // ✅ 用 get() 显示具体内容
      // 发送 POST 请求
      uploadFile(formData, {
        headers: {
          'Content-Type': 'multipart/form-data', // 设置请求头（可选，浏览器会自动处理）
        },
      })
        .then((response) => {
          if (response.code === 200) {
            // 假设后端返回成功状态码为 200
            this.handleDocSuccess(response);
          } else {
            this.handleDocError(response.msg || '上传失败');
          }
        })
        .catch((error) => {
          this.handleDocError(error.message || '上传失败');
        });
    },
    // 文件上传前的校验
    beforeDocUpload(file) {
      const isDocOrDocx = file.name.toLowerCase().endsWith('.doc') || file.name.toLowerCase().endsWith('.docx'); // 校验文件是否为doc或docx
      if (!isDocOrDocx) {
        this.$message.error('只能上传 DOC 或 DOCX 文件!');
      }
      return isDocOrDocx;
    },
    // 上传成功的回调
    handleDocSuccess(response) {
      this.$message.success('文件上传成功！');
      console.log('上传结果:', response);
      // 处理返回的数据
      const { url, fileName, newFileName, originalFilename } = response;
      console.log('文件 URL:', url);
      console.log('文件名:', fileName);
      console.log('新文件名:', newFileName);
      console.log('原始文件名:', originalFilename);
      this.project.docUrl = url;
      console.log('this.project.docUrl',this.project.docUrl)
      // this.closeDialog();
    },
    // 上传失败的回调
    handleDocError(errorMessage) {
      this.$message.error(`文件上传失败: ${errorMessage}`);
    },
  },
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.index1 h3 {
  margin-bottom: 8px;
}

.team-desc {
  margin-top: 8px;
}

.clickable {
  color: #409EFF;
  cursor: pointer;
  font-weight: bold;
}

.member-table {
  margin-top: 8px;
}

.footer-btn {
  text-align: center;
  margin-top: 20px;
}

.no-file {
  margin-left: 8px;
  color: #999;
}

.file-name {
  margin-left: 8px;
  color: #333;
}
</style>
